<?php

namespace app\api\controller;

use app\api\library\CommentException;
use app\common\library\HandleScoreService;
use think\Config;
use think\Exception;
use app\common\model\Comment as CommentModel;
use app\common\model\UserLike as UserLikeModel;

/**
 * 评论
 */
class Comment extends Base
{
    protected $noNeedLogin = ['index'];

    public function _initialize()
    {
        parent::_initialize();
        $type = $this->request->post("type", "news");
        if ($type == 'news') {
            //检测ID是否加密
            $this->hashids('aid');
        }
    }

    /**
     * 评论列表
     */
    public function index()
    {
        $aid = (int)$this->request->param('aid');
        $page = (int)$this->request->param('page');
        Config::set('paginate.page', $page);
        $commentList = \app\common\model\Comment::getCommentList(['aid' => $aid]);
        $commentList = $commentList->getCollection();
        foreach ($commentList as $index => $item) {
            if ($item->user) {
                $item->user->avatar = cdnurl($item->user->avatar, true);
                $item->user->visible(explode(',', 'id,nickname,avatar'));
            }
            $item->hidden(['ip', 'useragent', 'deletetime', 'aid', 'subscribe', 'status', 'type', 'updatetime']);
        }
        $this->success('', ['commentList' => $commentList]);
    }

    /**
     * 发表评论
     */
    public function post()
    {
        try {
            $params = $this->request->param();
            $comment = \app\common\model\Comment::postComment($params);//发表评论
            $comment->user->visible(explode(',', 'id,nickname,avatar'));
            $comment->user->avatar = cdnurl($comment->user->avatar, true);
        } catch (CommentException $e) {
            $this->success($e->getMessage(), ['__token__' => $this->request->token()]);
        } catch (Exception $e) {
            $this->error($e->getMessage(), ['__token__' => $this->request->token()]);
        }

        $this->success(__('评论成功'), ['comment' => $comment, '__token__' => $this->request->token()]);
    }

    //点赞
    public function doLike()
    {
        $userId = $this->auth->id;
//        $userId = 2;
        $articleId = $this->request->param('id', 0, 'intval');
        $type = $this->request->param('type', '');
        $type = $type ?? 'comment';
        $userLikeModel = new UserLikeModel();

        $findLikeCount = $userLikeModel->where([
            'user_id' => $userId,
            'object_id' => $articleId
        ])->where('table_name', 'comment')->count();

        if (empty($findLikeCount)) {
            $CommentModel = new CommentModel();
            $article = $CommentModel->where('id', $articleId)->field('id,post_title,post_excerpt')->find();

            if (empty($article)) {
                $this->error('评论不存在！');
            }

            Db::startTrans();
            try {
                $CommentModel->where('id', $articleId)->setInc('post_like');
                $thumbnail = empty(['thumbnail']) ? '' : ['thumbnail'];
                $userLikeModel->insert([
                    'user_id' => $userId,
                    'object_id' => $articleId,
                    'table_name' => $type,
                    'title' => $article['post_title'],
                    'thumbnail' => $thumbnail,
                    'description' => $article['post_excerpt'],
//                    'url'         => json_encode(['action' => 'portal/Article/index', 'param' => ['id' => $articleId, 'cid' => $article['categories'][0]['id']]]),
                    'create_time' => time()
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('点赞失败！');
            }

            $likeCount = $CommentModel->where('id', $articleId)->value('post_like');
            $this->success("赞好啦！", ['post_like' => $likeCount]);
        } else {
            $this->error("您已赞过啦！");
        }
    }

    /**
     * 取消评论点赞
     */
    public function cancelLike()
    {
        $userId = $this->auth->id;
//        $userId = 2;
        $articleId = $this->request->param('id', 0, 'intval');
        $type = $this->request->param('type', '');
        $type = $type ?? 'comment';
        $userLikeModel = new UserLikeModel();

        $findLikeCount = $userLikeModel->where([
            'user_id' => $userId,
            'object_id' => $articleId
        ])->where('table_name', $type)->count();

        if (!empty($findLikeCount)) {
            $CommentModel = new CommentModel();
            Db::startTrans();
            try {
                $CommentModel->where('id', $articleId)->setDec('post_like');
                $userLikeModel->where([
                    'user_id' => $userId,
                    'object_id' => $articleId
                ])->where('table_name', $type)->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('取消点赞失败！');
            }

            $likeCount = $CommentModel->where('id', $articleId)->value('post_like');
            $this->success("取消点赞成功！", ['post_like' => $likeCount]);
        } else {
            $this->error("您还没赞过！");
        }
    }
}
